<script>
import { ElSelect, ElOption } from 'element-plus'
import { watch, onBeforeMount, ref } from 'vue'
export default {
  name: 'SelectWidget',
  components: {
    ElSelect,
    ElOption
  },
  props: {
    modelValue: [String, Number],
    options: {
      type: [Array, Function],
      default: () => []
    }
  },
  setup(props, { attrs, emit }) {
    const opts = ref([])
    const handleOptions = async (options) => {
      if (Array.isArray(options)) {
        opts.value = [...options]
      } else {
        const res = await props.options()
        opts.value = res
      }
    }

    onBeforeMount(() => {
      handleOptions(props.options)
    })

    watch(
      () => props.options,
      (newOptions) => {
        handleOptions(newOptions)
      }
    )
    watch(
      () => props.modelValue,
      (newOptions) => {
        emit('update:modelValue', newOptions)
      }
    )

    return () => {
      return (
        <el-select {...attrs} model-value={props.modelValue}>
          {opts.value.map((item) => (
            <el-option {...item} key={item.value}></el-option>
          ))}
        </el-select>
      )
    }
  }
}
</script>
